﻿package src.zoo 
{
	import flash.utils.setInterval;
	import flash.utils.clearInterval;
	/**
	 * ...
	 * @author Yan
	 */
	internal class virtualPet 
	{
		private static var maxCalories = 2000;
		private static var nameLength = 20;
		private static var caloriesPerSecond = 100;
		
		private var petName;
		private var currentCalories = virtualPet.maxCalories / 2;
		private var digestIntervalID;
		
		public function virtualPet(name) 
		{
			setName(name);
			digestIntervalID = setInterval(digest, 1000);
		}
		public function eat(foodItem) 
		{
			// if the pet is dead
			if (currentCalories == 0)
			{
				//...quit this method without modifying currentcalories
				trace(getName() + "is dead. You can't feed it.");
				return;
			}
			
			if (foodItem is Apple)
			{
				if (foodItem.hasWorm())
				{
					trace("The" + foodItem.getName() + "had a worm." + getName() + "did't eat it.");
					return;
				}
			}
			
			var newCurrentCalories = currentCalories +foodItem.getCalories();
			if (newCurrentCalories > virtualPet.maxCalories) 
			{
				currentCalories = virtualPet.maxCalories;
			}else 
			{
				currentCalories = newCurrentCalories;
			}
			trace(getName() + "ate some "+foodItem.getName()+". It now has " + currentCalories + "calories remaining.");
			
		}
		
		public function getHunger() 
		{
			return currentCalories / virtualPet.maxCalories;
		}
		public function setName(newName)
		{
			if (newName.length > virtualPet.nameLength)
			{
				//truncate the name
				newName = newName.substr(0, virtualPet.nameLength);
			}else if (newName == "")
			{
				//terminate this method without changing petname
				return;
			}
			//assign the new, validated name to petname
			petName = newName;
		}
		public function getName()
		{
			return petName;
		}
		
		private function digest() 
		{
			//if digesting more calories would leave the pet's currentCalories at 0 or less...
			if (currentCalories - virtualPet.caloriesPerSecond <= 0)
			{
				//...stop the interval from calling digest()
				clearInterval(digestIntervalID);
				//then give the pet an empty stomach
				currentCalories = 0;
				//and report the pet's death
				trace(getName() + "has dead.");
			}else 
			{
				//...otherwise, digest the stipulated numnber of calories
				currentCalories -= virtualPet.caloriesPerSecond;
				
				//and report he pet's new status
				trace(getName() + "digest some food. It now has " + currentCalories + "calories remaining.");
			}
		}
		
	}
	
}